package com.scu.phototab.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.Gson;
import com.scu.phototab.enums.ResponseEnum;
import com.scu.phototab.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


/*
    为所有的/token/*的请求设定过滤器
 */
@Configuration
public class JwtFilter{

	private static String SERVER_SECRET;

	@Value("${serverSecret}")
	public void setServerSecret(String secret){
		JwtFilter.SERVER_SECRET = secret;
	}


	//注册token JWT过滤器
	@Bean
	public FilterRegistrationBean jwtFilterRegistrationBean(){
		FilterRegistrationBean bean=new FilterRegistrationBean(new jwtfilter());
		bean.addUrlPatterns("/session/token/*");
		bean.setName("JWTFilter");
		bean.setOrder(Integer.MAX_VALUE);
		return bean;
	}

	private static Algorithm algorithm = null;
	private static JWTVerifier verifier = null;

	@PostConstruct
	private void initAlgorithm(){
		try {
			algorithm = Algorithm.HMAC256(SERVER_SECRET);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		verifier = JWT.require(algorithm)
				.withIssuer("tianff.net")
				.build(); //Reusable verifier instance
	}


	public class jwtfilter implements Filter{

		@Override
		public void init(FilterConfig filterConfig) throws ServletException {

		}

		@Override
		public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
			final HttpServletRequest request = (HttpServletRequest) req;
			//	final HttpServletResponse response = (HttpServletResponse) res;
			final String authHeader = request.getHeader("authorization");


			if (authHeader == null || authHeader.length()==0) {
				errReturn(res,ResponseEnum.MISS_TOKEN);
				return;
			}

			try {
				System.out.println(SERVER_SECRET);
				System.out.println(authHeader);
				DecodedJWT jwt = verifier.verify(authHeader);

//				if (jwt.getExpiresAt().before(new Date(System.currentTimeMillis()))){
//					errReturn(res,ResponseEnum.OVER_TIME_TOKEN);
//					return;
//				}

				((HttpServletRequest) req).getSession().setAttribute("uid",jwt.getClaim("uid").asInt());
				chain.doFilter(req, res);

			} catch (final JWTVerificationException e) {
				errReturn(res,ResponseEnum.TOKEN_INVALID);
			}
		}

		@Override
		public void destroy() {

		}
		private void errReturn(ServletResponse servletResponse,ResponseEnum e) throws  IOException{
			servletResponse.setContentType("application/json;charset=utf-8");
			String res=new Gson().toJson(ResponseUtil.error(e));
			servletResponse.getWriter().append(res);
		}
	}


}
